<template>
  <div>
    <div class="bg-white h-auto my-2 mb-2 py-2">
      <BasicForm @register="registerForm" @submit="handleSubmit" />
    </div>
    <BasicTable
      @register="registerTable"
      :can-resize="true"
      :bordered="true"
      :striped="false"
      :loading="false"
      :data-source="SchedulesData.schedules"
    >
      <!-- 是否为节假日 -->
      <template #holidayFlag="{ record }">
        <template v-if="record.holiday === true">
          <Tag :color="'cadetBlue'">是</Tag>
        </template>
        <template v-if="record.holiday === false">
          <Tag :color="'DarkGray'">否</Tag>
        </template>
      </template>
      <template #toolbar>
        <a-button type="primary" @click="onBatchAddShift"> 设置排班班次 </a-button>
        <a-button type="primary" @click="onBatchAddShiftMembers"> 设置班次值班人员 </a-button>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditShift.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              label: '删除',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                confirm: onDeleteShift.bind(null, record),
              },
            },
            {
              icon: 'ant-design:audit-outlined',
              label: '班次人员管理',
              color: 'warning',
              onClick: onMembersTable.bind(null, record),
            },
          ]"
        />
      </template>
    </BasicTable>

    <batchAddShift @register="registerBatchAddShiftForm" @success="afterSuccess" />
    <batchAddShiftMembers @register="registerBatchAddShiftMembersForm" @success="afterSuccess" />
    <editShift @register="registerEditShiftForm" @success="afterSuccess" />
    <dutyScheduleMembersTable @register="registerMembersTable" @success="afterSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, provide, onBeforeMount, onUnmounted } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { Tag } from 'ant-design-vue';

  import { OperationTypeEnum } from '/@/enums/appEnum';

  import { useGlobSetting } from '/@/hooks/setting';

  import { query, deleteShift } from '/@/api/duty/dutySchedule';
  import { dutyScheduleTableColumns, scheduleQueryConditionFormSchema } from './dutyschedule.data';
  import { DutyScheduleQueryConditionDto } from '/@/api/duty/model/dutyScheduleModel';
  import { getByUserDept, getAllDutyGroup } from '/@/api/duty/dutygroup';

  import moment from 'moment';

  //引入子组件
  import batchAddShift from './BatchAddShift.vue';
  import batchAddShiftMembers from './BatchSetShiftMembers.vue';
  import editShift from './EditShift.vue';
  import dutyScheduleMembersTable from './DutyScheduleMembersTable.vue';

  //使用modal弹出窗口
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();

  const [registerBatchAddShiftForm, { openModal: openBatchAddShiftForm }] = useModal();
  const [registerBatchAddShiftMembersForm, { openModal: openBatchAddShiftMembersForm }] =
    useModal();
  const [registerEditShiftForm, { openModal: openEditShiftForm }] = useModal();
  const [registerMembersTable, { openModal: openMembersTable }] = useModal();

  export default defineComponent({
    name: 'DutyScheduleManagement',
    components: {
      BasicTable,
      BasicForm,
      TableAction,
      Tag,
      batchAddShift,
      batchAddShiftMembers,
      editShift,
      dutyScheduleMembersTable,
    },
    setup() {
      //定义模块的名称，提供给子孙组件获取使用
      const moduleName = ref('排班管理');
      provide('moduleName', moduleName);

      //处理过后的table数据
      const SchedulesData = reactive({
        schedules: [],
      });

      //获取项目编码
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);

      //查询接口的查询条件
      let time = new Date();
      let monthNum = moment().month();
      let queryConditionDto: DutyScheduleQueryConditionDto = {
        begintm: moment(time).month(monthNum).date(1).startOf('month').format('YYYY-MM-DD'), //默认当月第一天,
        endtm: moment(time).month(monthNum).date(1).endOf('month').format('YYYY-MM-DD'), //默认当月最后一天
        groupids: [],
      };

      onBeforeMount(() => {
        console.log('DOM即将挂载');
        getQuerySchedulesData();
      });
      onUnmounted(() => {
        console.log('销毁完毕');
      });

      const [registerForm, { updateSchema }] = useForm({
        labelWidth: 80,
        schemas: scheduleQueryConditionFormSchema,
        // actionColOptions: {
        //   span: 24,
        // },
      });

      /**
       * 请求后台查询接口返回数据显示
       */
      const [registerTable] = useTable({
        title: '排班管理',
        // api: query,
        // searchInfo: queryConditionDto,
        columns: dutyScheduleTableColumns, //表头数据
        // formConfig: {
        //   labelWidth: 100, //设置查询表单中label的宽度
        //   schemas: scheduleQueryConditionFormSchema, // form查询表单
        //   showResetButton: false, //查询条件部分中是否显示重置按钮
        // },
        // useSearchForm: true,
        showTableSetting: true, //是否显示表格设置
        showIndexColumn: true,
        actionColumn: {
          width: 220,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        pagination: false, //关闭分页
      });

      /**
       * 查询分组排班信息
       * （问题：会先执行查询数据接口，再获取分组id集合设置条件）
       * （解决：先获取分组id集合设为查询条件，再执行查询数据接口（async和await搭配使用））
       */
      async function getQuerySchedulesData() {
        if (queryConditionDto.groupids.length == 0) {
          //获取当前用户所在部门的所有分组id集合，设为查询条件
          //阳宗海的项目调用getByUserDept，其它项目调用getAllDutyGroup
          if (projectCode.value === 'yzh') {
            await getByUserDept()
              .then((res) => {
                // console.log('用户所在部门值班分组', res);
                //处理返回数据
                let gids = [];
                if (res != null) {
                  res.forEach((group) => {
                    let groupId = group.id;
                    gids.push(groupId);
                  });
                }
                queryConditionDto.groupids = gids;
                console.log('====queryConditionDto.groupids====', queryConditionDto.groupids);
              })
              .catch((ex) => {
                console.log('catch ', ex);
                // createMessage.error(ex.msg);
              });
          } else {
            await getAllDutyGroup()
              .then((res) => {
                // console.log('用户所在部门值班分组', res);
                //处理返回数据
                let gids = [];
                if (res != null) {
                  res.forEach((group) => {
                    let groupId = group.id;
                    gids.push(groupId);
                  });
                }
                queryConditionDto.groupids = gids;
                console.log('====queryConditionDto.groupids====', queryConditionDto.groupids);
              })
              .catch((ex) => {
                console.log('catch ', ex);
                // createMessage.error(ex.msg);
              });
          }
        }

        console.log('----queryConditionDto.groupids----', queryConditionDto.groupids);
        if (SchedulesData.schedules.length > 0) {
          SchedulesData.schedules = [];
        }

        //设置查询条件的值班分组下拉列表
        if (projectCode.value === 'yzh') {
          getDutyGroupsByUserDept();
        } else {
          getDutyGroups();
        }

        //调用接口查询方法
        getQueryData();
      }

      /**
       * 调用查询接口查询排班信息
       */
      function getQueryData() {
        //调用查询接口
        query(queryConditionDto)
          .then((res) => {
            console.log('res', res);
            if (res != null) {
              //处理返回数据
              if (res != null) {
                res.forEach((schedule) => {
                  let result = {
                    id: schedule.id,
                    groupid: schedule.groupid,
                    groupname: schedule.groupname,
                    begintm: schedule.begintm,
                    endtm: schedule.endtm,
                    holiday: schedule.holiday,
                    tmtext: schedule.tmtext,
                    membersName: '',
                  };
                  //处理成员列显示
                  if (schedule.members != null && schedule.members.length > 0) {
                    let members = schedule.members;
                    let nameStr = '';
                    members.forEach((teamMember) => {
                      if (teamMember.member != null) {
                        nameStr += teamMember.member.name + '，';
                      }
                    });
                    let index = nameStr.lastIndexOf('，');
                    result.membersName = nameStr.substring(0, index);
                  }
                  SchedulesData.schedules.push(result);
                });
              }
            }
            console.log('SchedulesData', SchedulesData);
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 获取当前用户所属部门的值班分组，用于下拉列表显示
       */
      function getDutyGroupsByUserDept() {
        //值班分组选项集合
        let groupOptions = [];
        getByUserDept()
          .then((res) => {
            console.log('res', res);
            res.forEach((group) => {
              //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
              groupOptions.push({ value: group.id, label: group.name });
            });

            //设置值班分组下拉列表
            updateSchema({
              field: 'groupids',
              componentProps: {
                options: groupOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 获取所有值班分组
       */
      function getDutyGroups() {
        //值班分组选项集合
        let groupOptions = [];
        getAllDutyGroup()
          .then((res) => {
            console.log('res', res);
            res.forEach((group) => {
              //options的value类型必须与表单中对应字段的类型一致，否则无法自动选中
              groupOptions.push({ value: group.id, label: group.name });
            });

            //设置值班分组下拉列表
            updateSchema({
              field: 'groupids',
              componentProps: {
                options: groupOptions,
              },
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            // createMessage.error(ex.msg);
          });
      }

      /**
       * 打开设置排班班次窗口
       */
      function onBatchAddShift() {
        //使用props传递数据至子组件，在data参数中指定
        openBatchAddShiftForm(true, { op: '设置排班班次' });
      }

      /**
       * 打开设置班次值班人员窗口
       */
      function onBatchAddShiftMembers() {
        //使用props传递数据至子组件，在data参数中指定
        openBatchAddShiftMembersForm(true, { op: '设置班次值班人员' });
      }

      /**
       * 打开班次编辑窗口
       */
      function onEditShift(record: Recordable) {
        openEditShiftForm(true, { op: OperationTypeEnum.EDIT, schedule: record });
      }

      /**
       * 打开班次人员管理弹窗
       */
      function onMembersTable(record: Recordable) {
        openMembersTable(true, { op: '班次人员管理', dataId: record.id });
      }

      /**
       * 删除班次
       */
      function onDeleteShift(record: Recordable) {
        deleteShift(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              getQuerySchedulesData();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 表单提交按钮事件
       */
      function handleSubmit(values: any) {
        console.log('表单数据', values);
        //设置表单数据为请求接口条件
        queryConditionDto.groupids = values.groupids;
        queryConditionDto.begintm = values.begintm;
        queryConditionDto.endtm = values.endtm;
        getQuerySchedulesData();
      }

      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        getQuerySchedulesData();
      }

      return {
        moduleName,
        registerForm,
        registerTable,
        afterSuccess,
        registerBatchAddShiftForm,
        registerBatchAddShiftMembersForm,
        registerEditShiftForm,
        registerMembersTable,

        onBatchAddShift,
        onBatchAddShiftMembers,
        onEditShift,
        onDeleteShift,
        handleSubmit,
        onMembersTable,

        getQueryData,
        getQuerySchedulesData,
        getDutyGroupsByUserDept,
        getDutyGroups,

        SchedulesData,
      };
    },
  });
</script>
